//
//  MVDetailViewController.m
//  花花时尚
//
//  Created by zhang on 15/10/6.
//  Copyright (c) 2015年 ggs. All rights reserved.
//

#import "MVDetailViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import "ArtistView.h"
#import "VideoMode.h"
#import "ArtistModel.h"
#import "AsyncGETConnection.h"
#import "Define.h"
#import "ArtistImageView.h"
#import "CommentTableViewCell.h"
#import "CommentModel.h"
#import "ArtistMVTableViewCell.h"
#import "AFNetworking.h"
#import "MJRefresh.h"
#import "NightMode.h"


@interface MVDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

{
    UIWindow *__sheetWindow ;//window必须为全局变量或成员变量
}
@property (nonatomic, retain)MPMoviePlayerController *MVPlayer;
@property (nonatomic, retain)NSMutableArray *array;
@property (nonatomic, retain)UIView *hoderView;
@property (nonatomic, retain)UITableView *commentTable;
@property (nonatomic, retain)UITableView *MVTable;
@property (nonatomic, retain)ArtistView *artistView;
@property (nonatomic, assign)CGFloat comHeight;//文本高度
@property (nonatomic, retain)NSMutableDictionary *dataDic;
@property (nonatomic, retain)UIView *backView;
@property (nonatomic, retain)UIActivityIndicatorView *activity;

@end

@implementation MVDetailViewController

static int i = 0;

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.MVArray = [NSMutableArray array];
        self.commentArray = [NSMutableArray array];
        self.video = [[[VideoMode alloc] init] autorelease];
        self.artist = [[[ArtistModel alloc] init] autorelease];
    }
    return self;
}

- (void)creatBackView
{
    self.backView = [[UIView alloc] initWithFrame:self.MVPlayer.view.frame];
    [self.view addSubview:self.backView];
    [self.backView release];
    
    self.activity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    self.activity.center = self.backView.center;
    self.activity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
    [self.backView addSubview:self.activity];
    [self.activity release];
    [self.activity startAnimating];
}

- (void)getConnectionWith:(NSInteger)number
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *path = [NSString stringWithFormat:@"http://mapi.yinyuetai.com/video/show.json?D-A=0&relatedVideos=true&id=%ld&%@", (long)number, deviceInfo];
    [manager GET:[NSString stringWithFormat:@"http://mapi.yinyuetai.com/video/show.json?D-A=0&relatedVideos=true&id=%ld&%@", (long)number, deviceInfo] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.dataDic = responseObject;
        NSLog(@"请求数据成功");
        NSLog(@"path = %@", path);
        NSArray *MVarray = [responseObject objectForKey:@"relatedVideos"];
        [self.MVArray addObjectsFromArray:MVarray];
        [self.MVTable reloadData];
        
        NSArray *artistArr = [responseObject objectForKey:@"artists"];
        
        [self.video setValuesForKeysWithDictionary:responseObject];
        self.video.descriptions = [responseObject objectForKey:@"description"];
        NSDictionary *artDic = [artistArr firstObject];
        self.artist.artistAvatar = [artDic objectForKey:@"artistAvatar"];
        [self.artist setValuesForKeysWithDictionary:artDic];
        //刷新赋值
        [self.artistView setvalueWith:self.video artist:self.artist];//艺术家界面赋值
        [self videoValue];//video赋值
        self.navigationItem.title = self.video.title;
        [self.backView removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求数据失败");
    }];
    
    //评论数据赋值
    NSString *path2 = [NSString stringWithFormat:@"http://mapi.yinyuetai.com/video/comment/list.json?D-A=0&v=2&offset=0&videoId=%ld&size=10&%@", number, deviceInfo];
    [manager GET:[NSString stringWithFormat:@"http://mapi.yinyuetai.com/video/comment/list.json?D-A=0&v=2&offset=0&videoId=%ld&size=10&%@", (long)number, deviceInfo] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"回复请求成功");
        NSLog(@"path2 = %@", path2);
        
        NSArray *commentArr = [responseObject objectForKey:@"comments"];
        [self.commentArray addObjectsFromArray:commentArr];
        [self.commentTable reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"回复请求失败");
    }];
    
}
- (void)creatHoderView
{
    self.hoderView = [[UIView alloc] initWithFrame:CGRectMake(0, 235 * REAL_HEIGTH, SCREEN_WIDTH, SCREEN_HEIGHT - 300 * REAL_HEIGTH - 30 * REAL_HEIGTH)];
    [self.view addSubview:self.hoderView];
    [self.hoderView release];
}
- (void)creatVideo
{
    self.MVPlayer = [[MPMoviePlayerController alloc] init];
    self.MVPlayer.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, 200 * REAL_HEIGTH);
    //    self.MVPlayer.view.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.MVPlayer.view];
    [self.MVPlayer release];
    [self creatBackView];
}

/*
 * video赋值uil
 */
- (void)videoValue
{
    NSURL *mvUrl = [NSURL URLWithString:self.video.hdUrl];
    [self.MVPlayer prepareToPlay];
    self.MVPlayer.contentURL = mvUrl;
}
- (void)creatSegmentedControl
{
    NSArray *nameArray = @[@"MV描述", @"评论", @"相关MV"];
    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:nameArray];
    seg.frame = CGRectMake(10 * REAL_WIDTH, 205 * REAL_HEIGTH, SCREEN_WIDTH - 20 * REAL_WIDTH, 30 * REAL_HEIGTH);
    seg.layer.cornerRadius = 5;
    seg.selectedSegmentIndex = 0;
    seg.tintColor = [UIColor colorWithRed:0.23 green:0.5 blue:0.82 alpha:0.9];
#warning 更改字体颜色美化UI!!!
    //    [seg setTitleTextAttributes:<#(NSDictionary *)#> forState:<#(UIControlState)#>];
    [seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:seg];
    [seg release];
    
}
- (void)segAction:(UISegmentedControl *)seg
{
    [self.hoderView removeFromSuperview];
    
    if (seg.selectedSegmentIndex == segIndex_Artist) {
        NSLog(@"进入艺术家界面");
        [self creatArtistView];
    } else if (seg.selectedSegmentIndex == segIndex_Comments) {
        NSLog(@"进入评论界面");
        [self creatCommentTable];
        
    } else if (seg.selectedSegmentIndex == segIndex_ArtMV) {
        NSLog(@"进入相关MV界面");
        [self creatMVTable];
    }
}

/*
 * 创建艺术家界面
 */
- (void)creatArtistView
{
    [self creatHoderView];
    self.artistView = [[ArtistView alloc] initWithFrame:CGRectMake(0, 0 , SCREEN_WIDTH, SCREEN_HEIGHT - 330 * REAL_HEIGTH)];
    self.artistView.headPic.target = self;
    self.artistView.headPic.action = @selector(jumpAction:);
    self.artistView.backgroundColor = [UIColor blackColor];
    [self.hoderView addSubview:self.artistView];
    //赋值
    [self.artistView setvalueWith:self.video artist:self.artist];
    [self.artistView release];
}

/*
 * 跳转入艺术家介绍界面
 */
- (void)jumpAction:(id)sender
{
//    DetailArtistViewController *detail = [[DetailArtistViewController alloc] init];
//    detail.artistId = self.artist.artistId;
//    [self.navigationController pushViewController:detail animated:YES];
}

/*
 * 创建评论界面
 */
- (void)creatCommentTable
{
    [self creatHoderView];
    self.commentTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.hoderView.frame.size.width, self.hoderView.frame.size.height - 20) style:UITableViewStylePlain];
    self.commentTable.tag = view_comment;
    self.commentTable.delegate = self;
    self.commentTable.dataSource = self;
    [self addFooter];
    [self addHeader];
    [self.hoderView addSubview:self.commentTable];
    [self.commentTable release];
}

- (void)addHeader{
    [self.commentTable addHeaderWithCallback:^{
        [self.commentTable reloadData];
        [self.commentTable headerEndRefreshing];
    }];
}

- (void)addFooter{
    [self.commentTable addFooterWithCallback:^{
        if (i == 0) {
            i += 5;
        } else {
            i += 10;
        }
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager GET:[NSString stringWithFormat:@"http://mapi.yinyuetai.com/video/comment/list.json?D-A=0&v=2&offset=%d&videoId=%ld&size=10&%@",i, self.id, deviceInfo] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"评论加载成功");
            if (responseObject == nil) {
                NSLog(@"没有更多评论");
            }
            NSArray *commentArr = [responseObject objectForKey:@"comments"];
            [self.commentArray addObjectsFromArray:commentArr];
            [self.commentTable reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"评论加载失败");
        }];
        [self.commentTable footerEndRefreshing];
    }];
}

/*
 * 创建MV界面
 */
- (void)creatMVTable
{
    [self creatHoderView];
    self.MVTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.hoderView.frame.size.width, self.hoderView.frame.size.height - 20) style:UITableViewStylePlain];
    self.MVTable.tag = view_MV;
    self.MVTable.rowHeight = 100;
    self.MVTable.delegate = self;
    self.MVTable.dataSource = self;
    [self.hoderView addSubview:self.MVTable];
    [self.MVTable release];
    
}

/*
 * 相关MV跳转播放
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == view_MV) {
        for (UIView *view in self.view.subviews) {
            if (view.tag == 100 || view.tag == 101) {
                
            } else {
                [view removeFromSuperview];
            }
        }
        NSDictionary *dic = [self.MVArray objectAtIndex:indexPath.row];
        NSInteger number = [[dic objectForKey:@"id"] integerValue];
        [self getConnectionWith:number
         ];
        [self creatVideo];
        [self creatSegmentedControl];
        [self creatArtistView];
    }
}

- (void)viewRoadDataWith:(NSDictionary *)dic
{
    self.MVPlayer.contentURL = [NSURL URLWithString:[dic objectForKey:@"url"]];
    VideoMode *video = [[VideoMode alloc] init];
    video.descriptions = [dic objectForKey:@"description"];
    [video setValuesForKeysWithDictionary:dic];
    ArtistModel *art = [[ArtistModel alloc] init];
    [art setValuesForKeysWithDictionary:dic];
    [self.artistView setvalueWith:video artist:art];
    [video release];
    [art release];
}

#warning ***Table协议实现****
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == view_comment) {
        return self.commentArray.count;
    } else {
        return self.MVArray.count;
    }
}
/*
 * 评论cell自适应高度
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag ==view_comment) {
        NSDictionary *dic = [self.commentArray objectAtIndex:indexPath.row];
        NSString *height = [dic objectForKey:@"content"];
        //文本高度
        CGFloat h = [MVDetailViewController heightWith:height];
        return h + 50 + 15 + 30;
    } else {
        return 100;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *endCell = [[UITableViewCell alloc] init];
    if (tableView.tag == view_comment) {
        static NSString *celll = @"celll";
        CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:celll];
        if (!cell) {
            cell = [[CommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:celll];
        }
        cell.backgroundColor = [UIColor blackColor];
        NSDictionary *comDic = [self.commentArray objectAtIndex:indexPath.row];
        CommentModel *commont = [[CommentModel alloc] init];
        [commont setValuesForKeysWithDictionary:comDic];
        CGFloat h = [MVDetailViewController heightWith:commont.content];
        [cell setValueWith:commont height:h];
        [commont release];
        endCell = cell;
    }
    else {
        static NSString *MVCelll = @"cellll";
        ArtistMVTableViewCell *MVCell = [tableView dequeueReusableCellWithIdentifier:MVCelll];
        if (!MVCell) {
            MVCell = [[ArtistMVTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MVCelll];
        }
        MVCell.backgroundColor = [UIColor yellowColor];
        NSDictionary *MVDic = [self.MVArray objectAtIndex:indexPath.row];
        MVCell.backgroundColor = [UIColor blackColor];
        VideoMode *video = [[VideoMode alloc] init];
        video.descriptions = [MVDic objectForKey:@"descriptions"];
        [video setValuesForKeysWithDictionary:MVDic];
        
        ArtistModel *art = [[ArtistModel alloc] init];
        art.artistName = [MVDic objectForKey:@"artistName"];
        [MVCell setvalueWith:video artist:art];
        
        [art release];
        [video release];
        
        endCell =  MVCell;
    }
    return endCell;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setNeedsDisplay];
    self.navigationController.navigationBar.barTintColor = [NightMode nightModeON]?[UIColor blackColor]:[UIColor whiteColor];
    UIImage * backImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"back":@"back_light" ofType:@"png"]];
    self.view.backgroundColor = [UIColor colorWithPatternImage:backImage];
    [self.MVTable reloadData];
    [self getConnectionWith:self.id];
    [self creatVideo];
    [self creatSegmentedControl];
    [self creatArtistView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 * 跳转停止视频播放
 */
- (void)viewDidDisappear:(BOOL)animated
{
    i = 0;
    [self.MVPlayer stop];
}
+ (CGFloat)heightWith:(NSString *)height
{
    //参数1: 预订的矩形大小
    //参数2: 图形选项
    //参数3: 属性字典(设置字体和字体大小,一般和cell中设置的一样)
    //参数4: 内容文本,一般设置为nil
    CGRect rect = [height boundingRectWithSize:CGSizeMake(300, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    
    return rect.size.height;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
